// pages/operation/signUp/signUpMain/index.js
import {
  SignUpModel
} from "../../../../api/api-work/signUpModel.js"
const signUpModel = new SignUpModel()
import {
  timestampToTime
} from "../../../../utils/index.js"
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    studentId: "", //学员id
    studentInfo: {}, //学员信息
    showReportedCourse: false, //已报读课程弹窗开关
    payType: "", //支付方式
    payTypeName: "", //支付方式回显
    payTypeList: [], //支付方式列表
    isShowPayType: false, //支付方式弹窗开关
    dealDate: null, //经办日期
    dealDateMS: "",
    isShowDealDate: false, //经办日期弹窗开关
    remark: "", //备注
    saleList: [{
      saler: "", //业绩归属人id
      salerName: "",
      courseAmount: "", //销售业绩
    }],
    saleDetial: "", //业绩归属人回显
    courseList: [], //已选课程列表
    priceTypeList: [], //定价标准列表
    isShowPriceType: false, //定价标准弹窗开关
    courseIndex: "", //选择定价标准所属课程下标
    payMoney: 0, //应收金额
    isShowExpireDate: false, //课程有效期弹窗开关
    minDate: new Date().getTime(), // 获取当前时间戳，禁用今日之前的日期

    /**转课退课 */
    operateType: 1, //操作类型
    checked: true,
    showRemoveCourse: false,
    removeCourseList: [], //已报课程列表转课退课使用
    courseId: "", //选中转出课程id
    courseName: "", //选中转出课程name
    orderList: [], //订单列表
    // enterMoney: 0, //转入金额
    outMoney: 0, //转出金额
    formattedAmount: 0, //计算金额
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const params = JSON.parse(options.param);
    this.setData({
      studentId: params.id,
      operateType: options.operateType,
      dealDate: this.formatDate(), //经办日期
    })
    console.log('operateType', this.data.operateType);
    if (this.data.operateType === '1') {
      wx.setNavigationBarTitle({
        title: '报名/续费'
      });
    } else if (this.data.operateType === '2') {
      wx.setNavigationBarTitle({
        title: '转课'
      });
    } else {
      wx.setNavigationBarTitle({
        title: '退课'
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    console.log('salerList', this.data.saleList);
    const allEmpty = this.data.saleList.every(item =>
      item.saler === ""
    );
    if (!allEmpty) {
      this.data.saleList.map((item, index) => {
        if (item.saler === "") {
          this.data.saleList.splice(index, 1)
        } else if (item.courseAmount == "") {
          item.courseAmount = "0"
        }
      })
      var query = this.data.saleList.map(item => `${item.salerName}(销售业绩${item.courseAmount}元)`).join("、");
      this.setData({
        saleDetial: query
      })
    } else {
      this.setData({
        saleDetial: "",
        saleList: [{
          saler: "", //业绩归属人id
          salerName: "",
          courseAmount: "", //销售业绩
        }],
      })
    }
    await this.getStudentInfo();
    await this.getPayType();
    if (this.data.operateType !== '1') {
      await this.getStudentCourseList();
    }
    // wx.getStorage({
    //   key: 'someKey',
    //   success: (res) => {
    //     console.log('回退传参', res.data);
    //   },
    // });
  },
  //获取学员基本信息
  async getStudentInfo() {
    signUpModel.getStudentInfoAPI({
      id: this.data.studentId
    }).then(res => {
      console.log('studentInfo', res);
      this.setData({
        studentInfo: res
      })
    })
  },
  //打开已报课程弹窗
  toShowReportedCourse() {
    this.setData({
      showReportedCourse: true
    })
  },
  //关闭已报课程弹窗
  onCloseReportedCourse() {
    this.setData({
      showReportedCourse: false
    })
  },

  //获取支付方式列表
  async getPayType() {
    signUpModel.getPayTypeAPI({
      lableType: "pay_type"
    }).then(res => {
      this.setData({
        payTypeList: res
      })
    })
  },
  //打开支付方式弹窗
  showPayTypePopup() {
    this.setData({
      isShowPayType: true
    })
  },
  //关闭支付方式弹窗
  onClosePayTypePopup() {
    this.setData({
      isShowPayType: false
    })
  },
  // 选择支付方式
  selectPayType(e) {
    const query = e.currentTarget.dataset.query;
    this.setData({
      isShowPayType: false,
      payType: query.id,
      payTypeName: query.name,
    })
  },
  //打开经办日期弹窗
  showDealDatePopup() {
    this.setData({
      isShowDealDate: true
    })
  },
  //关闭经办日期弹窗
  onCloseDealDatePopup() {
    this.setData({
      isShowDealDate: false
    })
  },
  formatDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },
  // 选中经办日期
  selectDealDate(e) {
    this.setData({
      dealDate: timestampToTime(e.detail),
      dealDateMS: e.detail,
      isShowDealDate: false
    })
  },
  //填写备注
  onChangeRemark(e) {
    this.setData({
      remark: e.detail
    })
  },
  //前往业绩归属人页面
  toSignUpSale() {

    const param = JSON.stringify(this.data.saleList)
    wx.navigateTo({
      url: `/pages/operation/signUp/signUpSale/index?param=${param}`,
    })
  },
  //前往选择课程页面
  toChooseOption() {
    wx.navigateTo({
      url: `/pages/operation/signUp/signUpOption/index`,
    })
  },

  //打开定价标准弹窗
  showPriceTypePopup(e) {
    console.log('index', e.currentTarget.dataset.query);
    const index = e.currentTarget.dataset.query
    this.setData({
      isShowPriceType: true,
      courseIndex: index,
      priceTypeList: this.data.courseList[index].tCoursePriceList
    })
  },
  //关闭定价标准弹窗
  onClosePriceTypePopup() {
    this.setData({
      isShowPriceType: false
    })
  },
  // 选择定价标准 
  selectPriceType(e) {
    const event = e.currentTarget.dataset.query;
    const query = this.data.courseList[this.data.courseIndex]
    query.tCoursePriceList
      .forEach((item) => {
        if (item.id === event.id) {
          query.relName = item.relName
          query.priceId = item.id
          query.courseAmount = item.totalPrice
          query.countLessonTotalNormal = item.num
          query.num = item.num
          if (item.num > 0) {
            query.originalUnitPrice = item.totalPrice / item.num
          } else {
            query.originalUnitPrice = item.totalPrice
          }
          query.discountAmount = item.discountedPrice
          query.countLessonTotalGive = item.freeClassHours ? item.freeClassHours : 0
          query.discountPrice = item.totalPrice - item.discountedPrice
        }
      })
    // this.data.payMoney = 0
    var payMoney = 0
    this.data.courseList.forEach((item) => {
      payMoney += parseInt(item.discountAmount)
    })
    const amount = payMoney - this.data.outMoney;
    console.log('payMoney', payMoney);
    this.setData({
      isShowPriceType: false,
      payMoney: payMoney,
      courseList: this.data.courseList,
      formattedAmount: amount % 1 === 0 ? Math.abs(amount) : Math.abs(amount).toFixed(2),
    });
  },
  //修改购买数量
  onChange1(e) {
    console.log('eeeeeeeeeeeeeeeee', e);
    const index = e.currentTarget.dataset.query
    const row = this.data.courseList[index]
    row.countLessonTotalNormal = e.detail
    row.courseAmount = row.countLessonTotalNormal * row.originalUnitPrice
    row.discountAmount = row.countLessonTotalNormal * row.originalUnitPrice - row.discountPrice
    var payMoney = 0
    this.data.courseList.forEach((item) => {
      payMoney += parseInt(item.discountAmount)
    })
    const amount = payMoney - this.data.outMoney;
    this.setData({
      courseList: this.data.courseList,
      formattedAmount: amount % 1 === 0 ? Math.abs(amount) : Math.abs(amount).toFixed(2),
      payMoney
    })
  },
  //修改赠送数量
  onChange2(e) {
    const index = e.currentTarget.dataset.query
    const item = this.data.courseList[index]
    item.countLessonTotalGive = e.detail
    item.unitPrice = (
      parseInt(item.discountAmount) /
      (parseInt(item.countLessonTotalNormal) +
        parseInt(item.countLessonTotalGive))
    ).toFixed(2)
    var payMoney = 0
    this.data.courseList.forEach((item) => {
      payMoney += parseInt(item.discountAmount)
    })
    const amount = payMoney - this.data.outMoney;
    this.setData({
      courseList: this.data.courseList,
      formattedAmount: amount % 1 === 0 ? Math.abs(amount) : Math.abs(amount).toFixed(2),
      payMoney
    })
  },
  //修改直减
  onChange3(e) {
    const index = e.currentTarget.dataset.query
    const row = this.data.courseList[index]
    row.discountPrice = e.detail
    row.discountAmount = row.courseAmount - row.discountPrice
    var payMoney = 0
    this.data.courseList.forEach((item) => {
      payMoney += parseInt(item.discountAmount)
    })
    const amount = payMoney - this.data.outMoney;
    this.setData({
      courseList: this.data.courseList,
      formattedAmount: amount % 1 === 0 ? Math.abs(amount) : Math.abs(amount).toFixed(2),
      payMoney
    })

  },
  //修改小计
  onChange4(e) {
    const index = e.currentTarget.dataset.query
    const row = this.data.courseList[index]
    row.discountAmount = e.detail
    row.discountPrice = row.courseAmount - row.discountAmount
    var payMoney = 0
    this.data.courseList.forEach((item) => {
      payMoney += parseInt(item.discountAmount)
    })
    const amount = payMoney - this.data.outMoney;
    this.setData({
      courseList: this.data.courseList,
      formattedAmount: amount % 1 === 0 ? Math.abs(amount) : Math.abs(amount).toFixed(2),
      payMoney
    })
  },
  //打开课程有效期弹窗
  showExpireDatePopup(e) {
    const index = e.currentTarget.dataset.query
    this.setData({
      isShowExpireDate: true,
      courseIndex: index
    })
  },
  //关闭课程有效期弹窗
  onCloseExpireDatePopup() {
    this.setData({
      isShowExpireDate: false
    })
  },
  // 选中课程有效期
  selectExpireDate(e) {
    console.log('eeeeeeeeeee', e);
    this.setData({
      [`courseList[${this.data.courseIndex}].expireDate`]: timestampToTime(e.detail),
      [`courseList[${this.data.courseIndex}].expireDateMS`]: e.detail,

      // expireDateMS:e.detail,
      isShowExpireDate: false
    })
  },
  //删除已选项目
  deleteCourse(e) {
    const index = e.currentTarget.dataset.query
    this.data.courseList.splice(index, 1)
    var payMoney = 0
    this.data.courseList.forEach((item) => {
      payMoney += parseInt(item.discountAmount)
    })
    const amount = payMoney - this.data.outMoney;
    this.setData({
      courseList: this.data.courseList,
      formattedAmount: amount % 1 === 0 ? Math.abs(amount) : Math.abs(amount).toFixed(2),
      payMoney
    })
  },


  /**转课部分 */
  //获取学员已报课程转课退课用
  async getStudentCourseList() {
    signUpModel.getStudentCourseListAPI({
      open: this.data.operateType === '2' ? 1 : 0,
      studentId: this.data.studentId
    }).then(res => {
      console.log('studentInfo', res);
      this.setData({
        removeCourseList: res
      })
    })
  },
  //打开转课退课已报课程弹窗
  toShowRemoveCourse() {
    this.setData({
      showRemoveCourse: true
    })
  },
  //关闭转课退课已报课程弹窗
  onCloseRemoveCourse() {
    this.setData({
      showRemoveCourse: false
    })
  },
  //选择转出课程获取订单
  async toSearchOrder(e) {
    console.log(e);
    this.setData({
      courseId: e.currentTarget.dataset.query.id,
      courseName: e.currentTarget.dataset.query.courseName,
      showRemoveCourse: false
    })
    signUpModel.getStudentCourseOrderListAPI({
      courseId: this.data.courseId,
      studentId: this.data.studentId
    }).then(res => {
      res.map(item => {
        item.orderSwitch = true
      })
      this.setData({
        orderList: res
      })
      var outMoney = 0;
      this.data.orderList.forEach((item) => {
        outMoney += parseInt(item.remainderAmount);
      });
      const amount = this.data.payMoney - outMoney;
      this.setData({
        formattedAmount: amount % 1 === 0 ? Math.abs(amount) : Math.abs(amount).toFixed(2),
        outMoney
      })
      // console.log('this.data.orderList', this.data.outMoney);
    })
  },
  //去订单详情
  toOrderDetails(e) {
    const param = JSON.stringify({
      id: e.currentTarget.dataset.query.id
    })
    wx.navigateTo({
      url: `/pages/operation/student/orderDetails/index?params=${param}`,
    })
  },
  //选中订单开关控制
  onChangeOrderSwitch(e) {
    console.log(e);
    this.setData({
      [`orderList[${ e.currentTarget.dataset.query}].orderSwitch`]: e.detail,
    })
    let numOrder = [];
    this.data.orderList.map((item) => {
      if (item.orderSwitch) {
        numOrder.push(item);
      }
    });
    var outMoney = 0;
    numOrder.forEach((item) => {
      outMoney += parseInt(item.remainderAmount);
    });
    const amount = this.data.payMoney - outMoney;
    this.setData({
      formattedAmount: amount % 1 === 0 ? Math.abs(amount) : Math.abs(amount).toFixed(2),
      outMoney
    })
    console.log('orderList', this.data.orderList);
  },
  //报名
  async toSignUp() {
    if (this.data.courseList.length) {
      Dialog.confirm({
          title: '你确定要报名吗?',
        })
        .then(() => {
          console.log('+++++++');
          this.data.courseList.map((item) => {
            item.unitPrice = (
              parseInt(item.discountAmount) /
              (parseInt(item.countLessonTotalNormal) +
                parseInt(item.countLessonTotalGive))
            ).toFixed(2);
            item.amount = item.discountAmount;
            item.paidAmount = item.discountAmount;
            item.payType = this.data.payType;
            item.remark = this.data.remark;
            delete item.id;
          });
          // this.data.saleList.map(item=>{
          //   delete item.salerName
          // })
          signUpModel.toSignUpAPI({
            handlingTime: this.data.dealDate,
            studentId: this.data.studentId,
            tStudentCourseVos: this.data.courseList,
            tStudentCourseSales: this.data.saleList,
          }).then(res => {
            Toast('课程购买成功');
            setTimeout(() => {
              wx.navigateBack({
                delta: 1,
              });
            }, 1000);
          })
        }).catch(() => {
          // on cancel
        });
    } else {
      Toast('请选择购买的项目');
    }
  },

  //转课
  toTransferOrder() {
    let selectOrder = [];
    this.data.orderList.map((item) => {
      if (item.orderSwitch) {
        selectOrder.push(item);
      }
    });
    if (this.data.courseList.length && selectOrder.length) {
      console.log(selectOrder);
      Dialog.confirm({
          title: '你确定要转课吗?',
        })
        .then(() => {
          let beyondLesson = [];
          selectOrder.map((item) => {
            if (item.remainderAmount < 0) {
              beyondLesson.push(item.remainderAmount);
            }
          });
          if (!beyondLesson.length) {
            this.data.courseList.map((item) => {
              item.unitPrice = (
                parseInt(item.discountAmount) /
                (parseInt(item.countLessonTotalNormal) +
                  parseInt(item.countLessonTotalGive))
              ).toFixed(2);
              item.amount = item.discountAmount;
              item.paidAmount = item.discountAmount;
              item.payType = this.data.payType;
              item.remark = this.data.remark;
              delete item.id;
            });
            const updatedOrders = selectOrder.map((item) => ({
              ...item,
              refundLessonNormal: item.remainderLessonNormal,
              refundLessonGive: item.remainderLessonGive,
              refundAmount: item.remainderAmount,
              handlingTime: this.data.dealDate,
              studentId: this.data.studentId,
              courseId: this.data.courseId,
              remark: this.data.remark,
            }));
            signUpModel.studentCourseTransferOrderAPI({
              tStudentCourseVos: updatedOrders,
              studentCourseVo: {
                handlingTime: this.data.dealDate,
                studentId: this.data.studentId,
                tStudentCourseVos: this.data.courseList,
                tStudentCourseSales: this.data.saleList,
              },
            }).then(res => {
              Toast('转课成功');
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1,
                });
              }, 1000);
            })
          } else {
            Toast('该学员所选课程下有超上课时,无法进行转课,请重新选择');
          }
        })
        .catch(() => {});
    } else {
      Toast('请选择转出转入课程');
    }
  },
  //退课
  toRefundOrder() {
    let selectOrder = [];
    this.data.orderList.map((item) => {
      if (item.orderSwitch) {
        selectOrder.push(item);
      }
    });
    if (selectOrder.length) {
      // console.log(selectOrder);
      Dialog.confirm({
          title: '你确定要退课吗?',
        })
        .then(() => {
          let beyondLesson = [];
          selectOrder.map((item) => {
            if (item.remainderAmount < 0) {
              beyondLesson.push(item.remainderAmount);
            }
          });
          if (!beyondLesson.length) {
            const updatedOrders = selectOrder.map((item) => ({
              ...item,
              refundLessonNormal: item.remainderLessonNormal,
              refundLessonGive: item.remainderLessonGive,
              refundAmount: item.remainderAmount,
              handlingTime: this.data.dealDate,
              studentId: this.data.studentId,
              courseId: this.data.courseId,
              remark: this.data.remark,
            }));
            signUpModel.studentCourseRefundOrderAPI(
              updatedOrders
            ).then(res => {
              Toast('退课成功');
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1,
                });
              }, 1000);
            })
          } else {
            Toast('该学员所选课程下有超上课时,无法进行退课,请重新选择');
          }
        })
        .catch(() => {});
    } else {
      Toast('请选择退出课程');
    }
  },

  //确认提交
  async toConfirm() {
    if (this.data.operateType === '1') {
      this.toSignUp()
    } else if (this.data.operateType === '2') {
      this.toTransferOrder()
    } else {
      this.toRefundOrder()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})